package io.renren.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.controller.im.TencentCloudImUtil;
import io.renren.dao.ImchatbillDao;
import io.renren.dto.*;
import io.renren.entity.ImchatbillEntity;
import io.renren.entity.ImgroupallbillEntity;
import io.renren.service.AutodecoratemService;
import io.renren.service.AutorepairmService;
import io.renren.service.ImchatbillService;
import cn.hutool.core.util.StrUtil;
import io.renren.service.ImgroupallbillService;
import io.renren.utils.FileUtil;
import io.renren.utils.WechatMsg;
import jdk.nashorn.internal.ir.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * IM 群聊历史记录
 *
 * @author Sen 524227263@qq.com
 * @since 1.0.0 2024-06-14
 */
@Service
public class ImchatbillServiceImpl extends CrudServiceImpl<ImchatbillDao, ImchatbillEntity, ImchatbillDTO> implements ImchatbillService {

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;
    @Autowired
    private ImgroupallbillService imgroupallbillService;

    @Override
    public QueryWrapper<ImchatbillEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<ImchatbillEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Autowired
    private AutorepairmService autorepairmService;
    @Autowired
    private AutodecoratemService autodecoratemService;

    @Override
    public int saveBill(String groupId) {
        List<ImResult> results = new ArrayList<>();
        Integer reqMsgSeq = null;
        boolean flag = false;
        List<ImMsgBody> rspMsgList;
        ImResult result;
        do {
            result = tencentCloudImUtil.adminGetQunRoamMsg(groupId, 15, reqMsgSeq);
            rspMsgList = result.getRspMsgList();
            if (rspMsgList != null) {
                // 移除指定对象
                rspMsgList.removeIf(imMsgBody -> imMsgBody.getIsPlaceMsg() != 0);
                int msgSize = rspMsgList.size();
                if (msgSize != 0) {
                    // 遍历消息，如果消息是图片，视频就保存文件服务器，返回地址，重新存进去
                    //                    rspMsgList = saveImgOrVideo(rspMsgList, groupId);
                    for (ImMsgBody body : rspMsgList) {
                        PortraitManageResult portraitManage = tencentCloudImUtil.getPortraitManage(body.getFrom_Account());
                        UserProfileBody userProfileBody = portraitManage.getUserProfileItem().get(0);
                        List<UserProfileItemBody> profileItemBody = userProfileBody.getProfileItem();
                        String nickName = profileItemBody.get(0).getValue();
                        body.setImNick(nickName);
                    }
                    result.setRspMsgList(rspMsgList);
                    results.add(result);
                    if (msgSize > 1) {
                        reqMsgSeq = rspMsgList.get(msgSize - 1).getMsgSeq() - 1;
                        if (reqMsgSeq == 0) {
                            // 说明消息读完了，跳出循环
                            flag = false;
                        } else {
                            // 否则继续读
                            flag = true;
                        }
                    } else {
                        flag = false;
                    }
                } else {
                    flag = false;
                }
            }
        } while (flag);

        QueryWrapper<ImchatbillEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(groupId), "Groupid", groupId);
        baseDao.delete(wrapper);

        ImgroupallbillEntity imgroupallbill = imgroupallbillService.findOneByImgroupid(groupId);

        ImchatbillEntity imchatbillEntity = new ImchatbillEntity();
        imchatbillEntity.setImchatmid(UUID.randomUUID().toString());
        imchatbillEntity.setChatBill(JSONObject.toJSONString(results));
        String autono = "";
        if (imgroupallbill != null) {
            String projectName = "";
            if (imgroupallbill != null) {
                String sourcebilltype = imgroupallbill.getSourcebilltype();
                String sourceBillOID = imgroupallbill.getSourcebilloid(); // 这个关联维修单表的AutoRepairMOID、美容单的AutoDecorateMOID
                /**
                 * 取维修、美容单上的项目名称ProjectName（多个项目用“分号”分隔）、门店名称orgName、金额repairAmount
                 * SourceBillType ： AAR   维修单 AutoRepairM
                 * SourceBillType ： AAD   美容单 AutoDecorateM
                 * SourceBillOID ： 这个关联维修单表的AutoRepairMOID、美容单的AutoDecorateMOID
                 */
                if ("AAR".equals(sourcebilltype)) {
                    // AutoRepairM
                    RepairDetailDto dtoAutoRepairM = new RepairDetailDto();
                    dtoAutoRepairM.setAutoRepairMoId(sourceBillOID);
                    Map<String, Object> autorepairm = autorepairmService.autoRepairDetail(null, dtoAutoRepairM);
                    if (autorepairm != null) {

                        String projectListStr = JSONObject.toJSONString(autorepairm.get("projectList"));

                        autono = JSONObject.toJSONString(autorepairm.get("GiveRepairTraderName"));
                        JSONArray jsonArray = JSONArray.parseArray(projectListStr);
                        StringBuilder resultBuilder = new StringBuilder();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            String itemProjectName = obj.getString("projectName");
                            if (i > 0) {
                                resultBuilder.append("; ");
                            }
                            resultBuilder.append(itemProjectName);
                        }

                        projectName = resultBuilder.toString();
                    }

                } else if ("AAD".equals(sourcebilltype)) {
                    // AutoDecorateM
                    DecorateDetailDto dtoAutoDecorateM = new DecorateDetailDto();
                    dtoAutoDecorateM.setAutoDecorateMoId(sourceBillOID);
                    Map<String, Object> autodecoratem = autodecoratemService.autoDecorateDetail(null, dtoAutoDecorateM);
                    if (autodecoratem != null) {
                        String projectListStr = JSONObject.toJSONString(autodecoratem.get("projectList"));
                        autono = JSONObject.toJSONString(autodecoratem.get("GiveRepairTraderName"));
                        JSONArray jsonArray = JSONArray.parseArray(projectListStr);
                        StringBuilder resultBuilder = new StringBuilder();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            String itemProjectName = obj.getString("projectName");
                            if (i > 0) {
                                resultBuilder.append("; ");
                            }
                            resultBuilder.append(itemProjectName);
                        }

                        projectName = resultBuilder.toString();
                    }
                }
            }

            imchatbillEntity.setRemark(projectName + ":" + groupId);
        }

        imchatbillEntity.setGroupid(groupId);
        imchatbillEntity.setSysCreated(new Date());
        imchatbillEntity.setAutono(autono);
        return baseDao.insert(imchatbillEntity);
    }

    @Override
    public List<ImResult> getListByGroupId(String groupId) {
        List<ImResult> results = new ArrayList<>();
        QueryWrapper<ImchatbillEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(groupId), "Groupid", groupId);
        List<ImchatbillEntity> list = baseDao.selectList(wrapper);
        String chatBill = list.size() > 0 ? list.get(0).getChatBill() : null;
        if (StringUtils.isNotEmpty(chatBill)) {
            results = JSONObject.parseArray(chatBill, ImResult.class);
        }
        return results;
    }

    @Override
    public List<ImchatbillEntity> getListByGroupIdPage(String keywords) {
        QueryWrapper<ImchatbillEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(keywords)) {
            wrapper.like("autono", keywords);
        }
        wrapper.orderByAsc("SYS_Created");
        return baseDao.selectList(wrapper);
    }

    private List<ImMsgBody> saveImgOrVideo(List<ImMsgBody> rspMsgList, String groupId) {
        rspMsgList.forEach(imMsgBody -> {
            try {
                List<MsgBody> msgBodys = JSONObject.parseArray(JSONArray.toJSONString(imMsgBody.getMsgBody()), MsgBody.class);
                if (msgBodys != null && msgBodys.get(0) != null) {
                    MsgBody msgBody = msgBodys.get(0);
                    String msgType = msgBody.getMsgType();
                    if (msgType != null) {
                        if ("TIMImageElem".equalsIgnoreCase(msgType)) {
                            ImgMsgContent img = JSON.parseObject(JSON.toJSONBytes(msgBody.getMsgContent()), ImgMsgContent.class);
                            List<ImgMsg> img1 = img.getImageInfoArray();
                            img1.forEach(imgMsg -> {
                                FileInputStream fileInputStream = null;
                                File fileByUrl = null;
                                try {
                                    // 根据url下载图片
                                    fileByUrl = FileUtil.getFileByUrl(imgMsg.getURL());
                                    fileInputStream = new FileInputStream(fileByUrl);
                                    String newName = DateUtil.currentSeconds() + "_" + imgMsg.getType() + FileUtil.getFileType(imgMsg.getURL());
                                    String fileObject = groupId + "/" + newName;
                                    // 存储图片
                                    // 更新图片地址
//                                            imgMsg.setURL(url);
                                } catch (Exception ignored) {
                                    // 如果出异常了，就不更新聊天记录的图片了
                                } finally {
                                    if (fileInputStream != null) {
                                        try {
                                            fileInputStream.close();
                                        } catch (IOException ignored) {
                                        }
                                    }
                                    if (fileByUrl != null) {
                                        fileByUrl.delete();
                                    }
                                }
                            });
                            img.setImageInfoArray(img1);
                            msgBody.setMsgContent(img);
                            msgBodys.clear();
                            msgBodys.add(msgBody);
                            imMsgBody.setMsgBody(msgBodys);

                        } else if ("TIMVideoFileElem".equalsIgnoreCase(msgType)) {
                            VedioMsgContent img = JSON.parseObject(JSON.toJSONBytes(msgBody.getMsgContent()), VedioMsgContent.class);
                            FileInputStream fileInputStream = null;
                            File fileByUrl = null;
                            try {
                                // 根据url下载图片
                                fileByUrl = FileUtil.getFileByUrl(img.getThumbUrl());
                                fileInputStream = new FileInputStream(fileByUrl);
                                String newName = DateUtil.currentSeconds() + "_Thumb" + FileUtil.getFileType(img.getThumbUrl());
                                String fileObject = groupId + "/" + newName;
                                // 存储图片

//                                        img.setThumbUrl(url);
                                try {
                                    fileInputStream.close();
                                } catch (IOException ignored) {
                                }
                                fileByUrl.delete();
                                // 根据url下载图片
                                fileByUrl = FileUtil.getFileByUrl(img.getVideoUrl());
                                fileInputStream = new FileInputStream(fileByUrl);
                                String newMp4Name = DateUtil.currentSeconds() + FileUtil.getFileType(img.getVideoUrl());
                                String mp4Object = groupId + "/" + newMp4Name;
                                // 存储图片

//                                        img.setVideoUrl(urlMp4);
                            } catch (Exception ignored) {
                                // 如果出异常了，就不更新聊天记录的文件
                            } finally {
                                if (fileInputStream != null) {
                                    try {
                                        fileInputStream.close();
                                    } catch (IOException ignored) {
                                    }
                                }
                                if (fileByUrl != null) {
                                    fileByUrl.delete();
                                }
                            }
                            msgBody.setMsgContent(img);
                            msgBodys.clear();
                            msgBodys.add(msgBody);
                            imMsgBody.setMsgBody(msgBodys);
                        }
                    }
                }
            } catch (Exception ignored) {
                // 报错说明消息不符合解析格式，不需要处理
            }
        });
        return rspMsgList;
    }
}